using System;
using System.Collections;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;

//CID 0230 //2009.02.25 //Begin
namespace InfoJetSoft.Service.Util
{
	/// <summary>
	/// Summary description for SDSUpdater.
	/// </summary>
	class SDSUpdater
	{
		public static void updateSDS( Form form )
		{
			IDictionaryEnumerator keyEnum = form.ParamTable.GetEnumerator();
			while( keyEnum.MoveNext() )
			{
				string paramKey = keyEnum.Key as string;
				string paramValue = keyEnum.Value as string;
				if( paramKey.StartsWith( "xdoc_s_" ) )
				{
					string jetId = paramKey.Substring( 4 );
					string attr = null;
					int atIndex = jetId.IndexOf( "@" );
					if( atIndex > 0 )
					{
						attr = jetId.Substring( atIndex + 1 );
						jetId = jetId.Substring( 0, atIndex );
					}
					
					XmlDocument dataDoc = findSDSDataDoc( form, jetId );	
					if( dataDoc != null )
					{
						XmlElement element = dataDoc.SelectSingleNode( "//*[@" + JetConstant.JetId + "='" + jetId + "']" ) as XmlElement;
						if( element != null )
						{
							if( attr == null )
							{
								DOMUtil.setNodeValue( element, paramValue );
							}
							else
							{
								//CID 0343 //2009.06.24 //Begin
								element.SetAttribute( attr, paramValue );
								//CID 0343 //2009.06.24 //End
							}
						}
					}
				}
			}
		}


		public static XmlDocument findSDSDataDoc( Form form, string jetId )
		{
			string jetIdWithoutPrefix = jetId.Substring( 3 );
			string sdsId = jetIdWithoutPrefix.Substring( 0, jetIdWithoutPrefix.IndexOf( "_" ) );
			foreach( DataObject dataObject in form.Manifest.DataObjectList )
			{
				if( dataObject.Id.Equals( sdsId ) )
				{
					return form.DataTable[ dataObject.Name ] as XmlDocument;
				}
			}
			return null;
		}
	}
}
//CID 0230 //2009.02.25 //End
